import axios from 'axios';

// 创建 Axios 实例
const api = axios.create({
//  baseURL: 'http://192.168.129.210:1999/',
    //  baseURL: 'http://8.138.12.59:1999/',  // API 基础地址
    //  baseURL: 'http://localhost:1999/',  // API 基础地址
    baseURL: 'http://113.45.144.121:1999',
    //  baseURL: 'http://192.168.101.176:1999/',

    timeout: 5000,  // 请求超时时间
    headers: {
        // 'Content-Type': 'multipart/form-data',
    },
});

export function getHomeDirections() {
    return api.get('/youxich/home/direction');
}

export function getCourseTeam(courseId) {
    return api.get('/youxich/home/courseteam', {
        params: {course_id: courseId}
    });
}

export function getPlatformData() {
    return api.get('/youxich/home/data');
}

// 获取课堂学期成绩与明星学生
export function getSemesterScore(semId) {
    return api.get('/youxich/semester/data/score', {
        params: {sem_id: semId}
    });
}

export function getActiveness(semId) {
    return api.get('/youxich/semester/data/activeness', {
        params: {sem_id: semId},
    });
}

export function getHmkScoreRate(semId) {
    return api.get('/youxich/semester/data/hmkScoreRate', {
        params: {sem_id: semId},
    });
}

export function getHmkLevel(semId) {
    return api.get('/youxich/semester/data/hmkLevel', {
        params: {sem_id: semId},
    });
}

// 上传头像接口
export function uploadAvatar(file) {
    const formData = new FormData();
    formData.append('file', file);  // 确保参数名称与接口文档一致

    return api.post('/youxich/upload', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    });
}

export function getFunctions() {
    return api.get('/youxich/home/function');
}

// 获取学生资源列表
export function fetchStudentResources(userId, resourceType) {
    return api.get('/youxich/resource/stu', {
        params: {
            userId: userId,
            resourceType: resourceType
        }
    });
}

// 学生收藏资源
export function collectStudentResource(data) {
    return api.post('/youxich/resource/stu', data, {
        headers: {
            'Content-Type': 'application/json'
        }
    });
}

// 流式问答接口
export function sendMessageToAI(message, user_id) {
    return api.post('/youxich/agent/answer', {
        msg: message,
        user_id: user_id,
    }, {
        headers: {
            'Content-Type': 'application/json',
        },
        responseType: 'stream',  // 设置为流式响应
    });
}

// 更新课堂信息
export function updateClassInfo(payload) {
    return api.put('/youxich/semester/personal', payload);
}

// 删除课堂
export function deleteClassById(semId) {
    return api.delete(`/youxich/semester/personal/${semId}`);
}

// 新增课堂接口
export function createClass(formData) {
    return api.post('/youxich/semester/personal', formData);
}

//上传封面附件
export function uploadcoverFile(file, status = 3) {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('status', status.toString());  // 确保status是字符串

    return api.post('/youxich/upload', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    });
}

// 获取教师的课堂数据
export function fetchClass(techId, semesterStatus) {
    return api.get('/youxich/semester/personal', {
        params: {
            tech_id: techId,
            semester_status: semesterStatus,
        },
    });
}

// 获取视频列表
export const fetchVideosApi = (techId, filterStatus, searchQuery, token) => {
    return api.get(`/youxich/resource/personal/video`, {
        params: {
            tech_id: techId,
            status: filterStatus,
            search: searchQuery,
        },
        headers: {
            Authorization: `Bearer ${token}`,
        },
    });
};

// 上传资源文件的接口
export function upload(formData) {
    return api.post('/youxich/resource/personal', formData, {
        headers: {
            'Content-Type': 'multipart/form-data', // 确保上传文件时使用正确的 Content-Type
        },
        timeout: 10000,
    });
}

export function uploadVideoApi(formData) {
    return api.post('/youxich/resource/personal/video', formData, {
        headers: {
            'Content-Type': 'multipart/form-data', // 确保上传文件时使用正确的 Content-Type
        },
    });
}

// 删除资源 API 调用
export const apiDeleteResource = (resourceId) => {
    return api.delete(`/youxich/resource/personal/${resourceId}`);
};

// 删除视频 API 调用
export const apiDeleteVideo = (videoid) => {
    return api.delete(`/youxich/resource/personal/video/${videoid}`);
};

// 重命名
export const apiRenameResource = (resourceId, resourceName) => {
    return api.put("/youxich/resource/personal", {
        resource_id: resourceId,
        resource_name: resourceName
    });
};
// 视频重命名
export const apiRenameVideo = (videoId, videoName) => {
    return api.put("/youxich/resource/personal/video", {
        resource_id: videoId,
        resource_name: videoName
    });
};

// 获取某种类型的资源
export function fetchResourcesByType(techId, resourceType, token) {
    return api.get('/youxich/resource/personal', {
        params: {
            tech_id: techId,
            resource_type: resourceType,
        },
        headers: {
            Authorization: `Bearer ${token}`,
        },
    });
}

// 获取 PPT 和 Word 两种资源
export function fetchAllResources(techId, token) {
    const pptRequest = api.get('/youxich/resource/personal', {
        params: {tech_id: techId, resource_type: 'ppt'},
        headers: {Authorization: `Bearer ${token}`},
    });

    const wordRequest = api.get('/youxich/resource/personal', {
        params: {tech_id: techId, resource_type: 'word'},
        headers: {Authorization: `Bearer ${token}`},
    });

    return Promise.all([pptRequest, wordRequest]);
}


// 获取课堂详情的 API 函数
export function fetchClassDetails(semesterId, techId) {
    return api.get(`/youxich/semester`, {
        params: {
            semester_id: semesterId,
            tech_id: techId,
        },
    });
}

// 获取通知公告
export function fetchNotices(semesterId) {
    return api.get('/youxich/notice', {
        params: {
            semester_id: semesterId,
        },
    });
}

// 获取分班列表的 API 函数
export function fetchDivisionList(semesterId) {
    console.log('Fetching Division List with semesterId:', semesterId); // 调试日志
    return api.get('/youxich/semester/division', {
        params: {
            semester_id: Number(semesterId), // 确保semester_id为整数
        },
    })
        .then(response => {
            console.log('Division List Response:', response.data); // 调试日志
            return response;
        })
        .catch(error => {
            console.error('Error in fetchDivisionList:', error); // 调试日志
            throw error;
        });
}

// 新增通知公告 API
export function createNotice(payload) {
    return api.post('/youxich/notice', payload);
}

// 更新通知公告 API
export function updateNotice(payload) {
    return api.put('/youxich/notice', payload);
}

// 删除通知公告 API
export function deleteNotice(noticeId) {
    return api.delete(`/youxich/notice/${noticeId}`);
}

// 获取作业列表 API
export function fetchAssignments(semesterId) {
    return api.get('/youxich/homework/teacher', {
        params: {
            semester_id: semesterId,
        },
    });
}

// 创建作业的API调用
export const ApicreateAssignment = (data) => {
    return api.post('/youxich/homework/teacher/base', data, {
        headers: {
            'Content-Type': 'multipart/form-data',
        },
    });
};

// 批量删除作业
export function deleteAssignments(homeworkIds) {
    return api.delete(`/youxich/homework/teacher/${homeworkIds.join(',')}`);
}

// 高级设置的API调用
export const updateAdvancedSettings = (data) => {
    return api.put('/youxich/homework/teacher', data, {
        headers: {
            'Content-Type': 'application/json',
        },
    });
};

// 高级设置回显
export function getAdvancedSettings(homeworkid) {
    return api.get('/youxich/homework/teacher/setting', {
        params: {
            homework_id: homeworkid,
        },
    });
}

export function fetchAssignmentOverview(homeworkId) {
    console.log('Fetching Assignment Overview with homeworkId:', homeworkId);
    return api.get('/youxich/homework/teacher/overview', {
        params: {
            homework_id: homeworkId, // 确保 homework_id 为字符串
        },
    })
        .then(response => {
            console.log('Assignment Overview Response:', response.data);
            return response;
        })
        .catch(error => {
            console.error('Error in fetchAssignmentOverview:', error);
            throw error;
        });
}

//学生列表
export const fetchStudentAssignments = (homeworkId, filters) => {
    return api.get(`/youxich/homework/teacher/grade`, {
        params: {
            homework_id: homeworkId,
            ...filters,
        },
    });
};

// 调分接口
export const adjustStudentScore = (data) => {
    return api.put(`/youxich/homework/teacher/grade`, data);
};


// 获取学生作业详情
export const fetchStudentAssignmentDetails = (stuHmwkId) => {
    return api.get(`/youxich/homework/teacher/grade/${stuHmwkId}`);
};

// 提交学生评阅
export const submitStudentGrade = (stuHmwkId, payload) => {
    return api.post(`/youxich/homework/teacher/grade/${stuHmwkId}`, payload);
};

// 获取学生作业评论列表
export const fetchComments = (stuHmwkId) => {
    return api.get(`/youxich/homework/teacher/grade/comment/${stuHmwkId}`);
};

// 获取作业详细
export function fetchAssignmentDetails(homeworkId) {
    return api.get(`/youxich/homework/teacher/base?homework_id=${homeworkId}`);
}

// 更新修改作业详细
export function updateAssignmentDetails(formData) {
    return api.put('/youxich/homework/teacher/base', formData);
}

//获取专业方向
export const getDirections = () => {
    return api.get('/youxich/home/direction');
};
//获取问题方向
export const getQuestionDirections = () => {
    return api.get('/youxich/home/qspoint');
};

export const fetchQuestions = async (params) => {
    return api.get(`/youxich/question/personal`, {params});
};


// 添加新题目的 API 函数
export const saveQuestion = (data) => {
    return api.post('/youxich/question/personal', data);
};

export const saveShortAnswerQuestionApi = async (data) => {
    try {
        return await api.post('/youxich/question/personal/qna', data);
    } catch (error) {
        console.error('Error in saveShortAnswerQuestionApi:', error.response?.data || error.message);
        throw error;
    }
};

// 获取单个试题
export function getSingleQuestion(qs_id) {
    return api.get(`/youxich/question/personal/${qs_id}`);
}

// 更新试题
export function updateQuestion(data, config = {}) {
    return api.put(`/youxich/question/personal`, data, config);
}

// 批量删除试题
export function batchDeleteQuestions(qs_ids) {
    return api.delete(`/youxich/question/personal/${qs_ids}`);
}

// 删除单个试题
export function deleteQuestion(qs_id) {
    return api.delete(`/youxich/question/personal/${qs_id}`);
}

// 新建试卷接口
export function createPaper(data) {
    return api.post('/youxich/paper/personal', data);
}

// 获取试卷数据
export function getPaperHeaders(params) {
    return api.get('/youxich/paper/personal', {params});
}

//获取试卷题型分类和题目信息
export function getPaperDetails(paperId) {
    return api.get(`/youxich/paper/personal/${paperId}`);
}

// 试卷头回显
export const getPaperHeader = (paperId) => {
    return api.get('/youxich/paper/personal/paperSetting', {
        params: {paper_id: paperId}  // 确保 paper_id 正确传递
    });
};

//更新试卷头部信息
export function updatePaperHeader(updatedHeader) {
    return api.put('/youxich/paper/personal/paperSetting', updatedHeader);  // 尝试 PUT 方法
}

//gen更新试卷题型命名
export function updatequestionformat(data) {
    return api.patch('/youxich/paper/personal/qsformat', data);
}

// 更新题目分数接口
export function updateQuestionScore(qs_id, paper_id, max_score) {
    return api.patch('/youxich/paper/personal/qsmaxscore', {
        qs_id,
        paper_id,
        max_score,
    });
}

// 生成AI问题接口
export function generateAIQuestion(params) {
    return api.post('/youxich/agent/qs', params, {
        timeout: 30000  // 单独为AI接口设置更长超时
    });
}

// 更新题目详细信息接口
export function updateQuestionDetail(data) {
    return api.patch('/youxich/paper/personal/qs', data);
}

// 教师从题库批量添加题目
export function addQuestionsToPaper(data) {
    return api.post('/youxich/paper/qs/many', data);
}

// 批量删除试卷
export function deletePerper(paperids) {
    return api.delete(`/youxich/paper/personal/${paperids}`);
}

//试卷库添加题目
export const addQuestionToBackend = (data) => {
    return api.post('/youxich/paper/qs', data);
};

// 试卷删除题目
export function deletePaperQuestion(paperQsIds) {
    return api.delete(`/youxich/paper/personal/qs/${paperQsIds}`);
}

// 添加考试分数修改接口
export const updateExamScores = (data) => {
    return api.patch('/youxich/exam/teacher/paper/anslist', data, {
        headers: {
            'Content-Type': 'application/json'
        }
    });
};

// 获取在线考试列表
export function fetchExams(semesterId, status = null) {
    return api.get('/youxich/exam/teacher', {
        params: {
            sem_id: semesterId,
            status: status,
        },
    });
}

// 创建试卷（课堂）
export function createExamWithClass(data) {
    return api.post('/youxich/exam/teacher/new', data);
}

// 批量删除课堂考试
export function deleteExams(examIds) {
    return api.delete(`/youxich/exam/teacher/${examIds}`);
}

//AI课堂摘要
export function ClassSummry(data) {
    return api.post('/youxich/agent/intro', data);
}

// 获取考试规则设置
export function getExamSettings(examId) {
    return api.get('/youxich/exam/teacher/paper/rule', {
        params: {
            exam_id: examId
        }
    });
}

// 更新考试规则设置
export function updateExamSettings(data) {
    return api.post('/youxich/exam/teacher/paper/rule', data, {
        headers: {
            'Content-Type': 'application/json'
        }
    });
}


//选试卷
export const createexamwithexistingpaper = (data) => {
    return api.post('/youxich/exam/teacher/ready', data);
};

// 获取答题列表
export const fetchExamAnswerList = (params) => {
    return api.get('/youxich/exam/teacher/paper/anslist', {
        params: {
            division_id: params?.division_id,
            submit_status: params?.submit_status,
            mark_status: params?.mark_status,
            exam_id: params.exam_id // 必填参数
        }
    });
};

// 获取学生答题详情
export const fetchAnswerReviewDetail = (params) => {
    return api.post('/youxich/exam/teacher/paper/anslist/detail', {
        sem_id: params.sem_id,
        stu_exam_id: params.stu_exam_id,
        paper_id: params.paper_id
    }, {
        headers: {
            'Content-Type': 'application/json'
        }
    });
};

// 获取考试试卷概览数据
export function fetchPaperData(examId, semId) {
    return api.get('/youxich/exam/data/paperdata', {
        params: {exam_id: examId, sem_id: semId}
    });
}

// 获取考试分班比对数据
export function fetchDivisionData(examId, semId) {
    return api.get('/youxich/exam/data/divisiondata', {
        params: {exam_id: examId, sem_id: semId}
    });
}

// 获取考试知识点词云数据
export function fetchPointData(examId) {
    return api.get('/youxich/exam/data/pointdata', {
        params: {exam_id: examId}
    });
}

// 获取学生优良中差数据
export function fetchScoreData(examId, semId) {
    return api.get('/youxich/exam/data/scoredata', {
        params: {exam_id: examId, sem_id: semId}
    });
}

export function fetchChapters(semId) {
    return api.get('/youxich/unit', {
        params: {sem_id: semId}
    });
}

export function fetchChapterResources(unitId) {
    return api.get(`/youxich/unit/${unitId}`);
}

// 考试试题列表接口
export function fetchQuestionList(examId, semId) {
    return api.get('/youxich/exam/qs/list', {
        params: {
            exam_id: examId,
            sem_id: semId
        }
    });
}

// 试题详情接口
export function fetchQuestionDetail(examId, semId, qsId, qsType) {
    return api.get('/youxich/exam/qs/detail', {
        params: {
            exam_id: examId,
            sem_id: semId,
            qs_id: qsId,
            qs_type: qsType
        }
    });
}

// 批阅学生考试得分
export function submitExamScores(payload) {
    return api.patch('/youxich/exam/teacher/paper/anslist', payload);
}

//章节增删改查
export function createChapter(params) {
    return api.post('/youxich/unit/teacher', params);
}

export function createSection(params) {
    return api.post('/youxich/unit/teacher', params);
}

export function renameUnit(params) {
    return api.patch('/youxich/unit/teacher', params);
}

export function deleteUnits(ids) {
    return api.delete(`/youxich/unit/teacher/${ids}`);
}

export function addResourceToSection(params) {
    return api.post('/youxich/unit/teacher/resource', params);
}

export function deleteResources(ids) {
    return api.delete(`/youxich/unit/teacher/resource/${ids}`);
}

export function getSurveyList(semId, status = null) {
    return api.get('/youxich/survey/sem', {
        params: {
            semId: semId,   // 学期 ID
            status: status, // 可选，筛选问卷的状态
        }
    });
}

// 创建新问卷
export function createNewSurveyAPI(surveyData) {
    return api.post('/youxich/survey/sem', surveyData);
}

// 新增问卷接口 
export function fetchSurveys(techId) {
    return api.get('/youxich/survey', {
        params: {
            tech_id: techId
        }
    });
}

// 新增问卷接口
export function createSurvey(data) {
    return api.post('/youxich/survey', {
        paper_title: data.paper_title,
        paper_content: data.paper_content,
        sem_id: data.sem_id,
        tech_id: data.tech_id
    });
}

//获取教师端问卷分析数据
export function fetchSurveyAnalysis(semId, surveyId) {
    return api.get(`/youxich/survey/sem/list?sem_id=${semId}&survey_id=${surveyId}`);
}

// 添加发布问卷接口
export function publishSurveyAPI(data) {
    return api.post('/youxich/survey/sem/setting', data);
}

//删除问卷
export function deleteSurvey(survey_ids) {
    return api.delete(`/youxich/survey/sem/${survey_ids}`);
}

//学生端
// 获取学生的课堂列表
export const getStudentClasses = (user_id, semester_status) => {
    return api.get('/youxich/semester/stu', {
        params: {
            user_id,
            semester_status: semester_status || 0 // 处理空值情况
        }
    });
};

// 获取课堂详细
export function StufetchClassDetails(semesterId, stuId) {
    return api.get(`/youxich/semester/stu/detail`, {
        params: {
            semester_id: semesterId,
            stu_id: stuId,
        },
    });
}

//加入课堂
export const joinClass = (data) => {
    return api.post('/youxich/semester/stu', {
        semester_code: data.class_code, // 修正参数名
        user_id: data.stu_id
    });
};

// 添加学生试题库接口
export function StufetchQuestions(params) {
    return api.get('/youxich/question/stu', {
        params: {
            user_id: localStorage.getItem('id'), // 从本地存储获取用户ID
            qs_type: params.qs_type || '',
            difficulty: params.difficulty || '',
            point_id: params.point_id || ''
        }
    });
}

// 添加收藏
export function addStudentFavorite({user_id, resource_id}) {
    return api.post('/youxich/resource/stu', {user_id, resource_id});
}

// 取消收藏
export function removeStudentFavorites(reStarIds) {
    return api.delete(`/youxich/resource/stu/${reStarIds}`);
}

// 试题收藏接口
export function addQuestionFavorite(data) {
    return api.post('/youxich/question/stu', data);
}

// 取消试题收藏接口
export function removeQuestionFavorites(qs_star_id) {
    return api.delete(`/youxich/question/stu/${qs_star_id}`);
}

//拉学生端的小节列表
export function fetchStudentChapters(sem_id, user_id) {
    return api.get('/youxich/unit/stu', {
        params: {
            sem_id,
            user_id
        }
    });
}

//拉学生端的小节资源
export function StufetchStudentResources(unit_id, user_id) {
    return api.get('/youxich/unit/stu/resource', {
        params: {
            unit_id,
            user_id
        }
    });
}

// 获取作业列表 API
export function StufetchAssignments(semesterId, user_id) {
    return api.get('/youxich/homework/stu', {
        params: {
            semester_id: semesterId,
            user_id: user_id,
        },
    });
}

// 获取学生作业列表 API
export function StuAssignment(user_id, hmk_id) {
    return api.get('/youxich/homework/stu/review', {
        params: {
            user_id: user_id,
            hmk_id: hmk_id,
        },
    });
}

// 获取学生作答详情 API
export function StufetchStudentDetails(stu_hmwk_id) {
    return api.get('/youxich/homework/stu/submit', {
        params: {
            stu_hmwk_id: stu_hmwk_id,
        },
    });
}

//上传附件
export function uploadFile(file, status = 2) {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('status', status.toString());  // 确保status是字符串

    return api.post('/youxich/upload', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    });
}

// 学生作业提交接口
export function submitHomework(payload) {
    return api.post('/youxich/homework/stu/submit', {
        hmk_id: payload.hmk_id,
        content: payload.content,
        attachment_url: payload.attachment_url,
        user_id: payload.user_id,
        is_remit: payload.is_remit
    }, {
        headers: {
            'Content-Type': 'application/json'
        }
    });
}

// 更新作业
export function updateStudentAssignment(stu_hmwk_id, content, attachment_url) {
    return api.put('/youxich/homework/stu/submit', {
        stu_hmwk_id,
        content,
        attachment_url
    });
}

// 学生考试列表
export function fetchStuExams(semesterId, status = null, userId) {
    return api.get('/youxich/exam/stu', {
        params: {
            sem_id: semesterId,
            status: status,
            user_id: userId,
        },
    });
}

// 提交学生的作答
export function StusubmitExam(data) {
    return api.post('/youxich/exam/stu', data);
}

//回显
export function fetchStuExamDetail(paper_id, semester_id, stu_exam_id, user_id) {
    return api.post('/youxich/exam/stu/detail', {
        paper_id,
        sem_id: semester_id,
        stu_exam_id,
        user_id,
    });
}

// 获取互评作业列表（学生视角）
export function fetchEachReviewList(hmk_id, user_id) {
    return api.get('/youxich/homework/stu/each', {
        params: {
            hmk_id,
            user_id
        }
    });
}

// 获取互评回显
export function fetchEachReviewDetail(stu_hmk_id, user_id) {
    return api.get('/youxich/homework/stu/each/detail', {
        params: {stu_hmk_id, user_id}
    });
}

//学生数据分析
export function getStuSemesterData(stu_id, semester_id) {
    return api.get('/youxich/semester/stu/data', {
        params: {
            stu_id,
            semester_id,
        },
    });
}

//学生问卷
export function getStuSurveyList(userId, semId, status = null) {
    return api.get('/youxich/survey/stu', {
        params: {
            user_id: userId,
            sem_id: semId,
            status: status
        }
    });
}

export function getSurveyDetail(payload) {
    return api.post('/youxich/survey/stu/detail', payload);
}

export function submitSurvey(payload) {
    return api.post('/youxich/survey/stu', payload);
}

// 获取学生列表
export function fetchStudentList(semesterId, divisionId, search = '', page = 1, limit = 5) {
    return api.get('/youxich/semester/division/list', {
        params: {
            sem_id: semesterId,
            division_id: divisionId,
            search: search,
            page: page,
            limit: limit,
        },
    });
}

// 新建分班
export function createNewGroupAPI(newGroup) {
    return api.post('/youxich/semester/division', newGroup);
}

// 修改学生分班
export function changeStudentGroup(stuSemesterId, divisionId) {
    return api.put('/youxich/semester/division', {
        stu_semester_id: stuSemesterId,
        division_id: divisionId,
    });
}

// 学生退出班级
export function exitClassAPI(stuSemesterId) {
    return api.delete(`/youxich/semester/stu/${stuSemesterId}`);
}

// 响应拦截器 (统一处理错误)
// 请求拦截器 (添加 Token)
api.interceptors.request.use(
    (config) => {
        try {
            const token = localStorage.getItem('token');
            if (token) {
                // 如果有 Token，添加到请求头
                config.headers.token = `Bearer ${token}`;
            }
            return config;

        } catch (error) {
            // 捕获异常并打印错误信息
            console.error('请求拦截器中发生错误:', error);
            throw error;  // 抛出错误，方便进一步处理
        }
    },
    (error) => {
        console.error('请求拦截器错误:', error); // 打印错误信息
        return Promise.reject(error);
    }
);


export default api;
